<?php
namespace app\index\controller\wanlshop;

use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

use addons\wanlshop\library\WanlChat\WanlChat;
use app\common\controller\Wanlshop;
use addons\wanlshop\library\WanlSdk\Ehund; //快递100订阅

use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    protected $searchFields = 'user.mobile,user.username';
    /**
     * Order模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Order;
        $kuaidi = new \app\index\model\wanlshop\Kuaidi;
        $this->wanlchat = new WanlChat();
        $this->view->assign("kuaidiList", $kuaidi->field('name,code')->select());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statesList", $this->model->getStatesList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user','ordergoods'])
                ->where($where)
                ->join("wanlshop_order_goods b","wr_wanlshop_order.id = b.order_id")
                ->where("b.goods_id","<>",873)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user','ordergoods'])
                ->where($where)
                ->join("wanlshop_order_goods b","wr_wanlshop_order.id = b.order_id")
                ->where("b.goods_id","<>",873)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['id','username','nickname','avatar','mobile']);
                $mypay = model('app\index\model\wanlshop\Pay')
                    ->where(['order_id' => $row['id'], 'type' => 'goods'])
                    ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                    ->find();
                if(!$mypay){
                    $row->pay = [
                        "pay_no"=>"","price"=>"","order_price"=>"","freight_price"=>"","discount_price"=>"","actual_payment"=>""
                    ];
                }else{
                    $row->pay = $mypay;
                }

            }
            $list = collection($list)->toArray();


            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($id = null, $order_no = null)
    {
        $where = $order_no ? ['order_no' => $order_no] : ['id' => $id];
        $row = $this->model
            ->where($where)
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断权限
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        $row['address'] = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        $mypay = model('app\index\model\wanlshop\Pay')
            ->where(['order_id' => $row['id'], 'type' => 'goods'])
// 			->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
            ->find();
        if(!$mypay){
            $row['pay'] = [
                "pay_type"=>"","pay_no"=>"","order_price"=>"","freight_price"=>"","discount_price"=>"","actual_payment"=>"","price"=>"","pay_type_text"=>"","trade_no"=>"","pay_state_text"=>""
            ];
        }else{
            $row['pay'] = $mypay;
        }

        $row['user'] = db("user")
            ->where("id",$this->auth->id)
            ->find();

        // 查询快递状态
        switch ($row['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $row['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['paymenttime'])
                ];
                break;
            default: // 获取物流
                $eData = model('app\api\model\wanlshop\KuaidiSub')
                    ->where(['express_no' => $row['express_no']])
                    ->find();
                if($eData){
                    // 获取数据 兼容PHP7.4	1.1.5升级
                    $ybData = json_decode($eData['data'], true);
                    if(!empty($ybData)){
                        // 运单状态 1.0.6升级
                        $statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
                        $status = $statusText[0];
                        if(in_array('status', $ybData[0])){
                            $status = $ybData[0]['status'];
                        }else{
                            if($eData['ischeck'] === 1){
                                $status = $statusText[3];
                            }else{
                                $status = $statusText[$eData['state']];
                            }
                        }
                        $express = [
                            'status' => $status,
                            'context' => $ybData[0]['context'],
                            'time' => $ybData[0]['time'],
                        ];
                    }
                }
                $express = [
                    'status' => '已发货',
                    'context' => '包裹正在等待快递小哥揽收~',
                    'time' => date('Y-m-d H:i:s', $row['delivertime'])
                ];
        }
        $this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        // return json($row);
        return $this->view->fetch();
    }

    /**
     * 快递查询
     */
    public function relative($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断权限
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        $data = model('app\index\model\wanlshop\KuaidiSub')
            ->where(['express_no' => $row['express_no']])
            ->find();
        $list = [];
        $week = array("0"=>"星期日","1"=>"星期一","2"=>"星期二","3"=>"星期三","4"=>"星期四","5"=>"星期五","6"=>"星期六");
        if($data){
            // 兼容PHP7.4	1.1.6升级
            $ybData = json_decode($data['data'], true);
            if(!empty($ybData)){
                foreach($ybData as $vo){
                    $list[] = [
                        'time' => strtotime($vo['time']),
                        'status' => in_array('status', $vo) ? $vo['status'] : '在途', // 1.0.6升级
                        'context' => $vo['context'],
                        'week' => $week[date('w', strtotime($vo['time']))]
                    ];
                }
            }
        }
        $this->view->assign("week", $week);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 打印发货单 1.1.2升级
     */
    public function invoice($ids = null)
    {
        $list = $this->model->all($ids);
        if (!$list) {
            $this->error(__('No Results were found'));
        }
        foreach ($list as $row) {
            // 判断权限
            if ($row['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $row['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
            $row['pay'] = model('app\index\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->field('id,number,actual_payment,order_price,freight_price,discount_price,price')
                ->find();
        }
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }

    /**
     * 发货 & 批量发货
     */
    public function delivery($ids = null)
    {
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data = [];
        $lists = [];
        $mobile = [];
        foreach ($row as $vo) {
            if ($vo['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $address = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $vo['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
            $vo['address'] = $address;
            if ($vo['state'] == 2) {
                $lists[] = $vo;
            } else {
                $data[] = $vo;
            }
            $mobile[$vo['id']] = $address['mobile'];
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if (!array_key_exists("order", $request['row'])) {
                $this->success(__('没有发现可以发货订单~'));
            }
            if(!$this->wanlchat->isWsStart()){
                $this->error('平台未启动IM即时通讯服务，暂时不可以发货');
            }
            $config = get_addon_config('wanlshop');
            $ehund = new Ehund($config['kuaidi']['secretKey'], $config['ini']['appurl'].$config['kuaidi']['callbackUrl']);
            $order = [];
            $express = [];
            foreach ($request['row']['order']['id'] as $key => $id) {
                $express_no = $request['row']['order']['express_no'][$key];
                $express_name = $request['row']['express_name'];
                $order[] = [
                    'id' => $id,
                    'express_name' => $express_name,
                    'express_no' => $express_no,
                    'delivertime' => time(),
                    'state' => 3
                ];
                // 1.0.5升级 查询是否存在,如果存在绕过快递100订阅
                $is_express_no = model('app\index\model\wanlshop\KuaidiSub')->where(['express_no' => $express_no])->count();
                // 订阅快递查询
                if ($config['kuaidi']['secretKey'] && $is_express_no == 0 && $express_name !== 'ziti') {
                    $returncode = $ehund->subScribe($express_name, $express_no, $mobile[$id]);
                    if(!$returncode){
                        $this->error('快递订阅接口异常-可能后台没有配置正确的快递100SDK');
                    }
                    if ($returncode['returnCode'] != 200 && $returncode['returnCode'] != 501) {
                        $this->error('快递订阅接口异常-'.$returncode['message']);
                    }
                    if($returncode['returnCode'] == 501){
                        $express[] = [
                            'sign' => $ehund->sign($express_no),
                            'express_no' => $express_no,
                            'returncode' => 200,
                            'message' => "发货成功"
                        ];
                    }else{
                        $express[] = [
                            'sign' => $ehund->sign($express_no),
                            'express_no' => $express_no,
                            'returncode' => $returncode['returnCode'],
                            'message' => $returncode['message']
                        ];
                    }

                }
                // 推送消息
                $this->pushOrder($id,'已发货');
            }
            // 使用事务 1.1.2升级
            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->saveAll($order);
                // 写入快递订阅列表
                if ($express) model('app\index\model\wanlshop\KuaidiSub')->saveAll($express);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            // 判断是否支付成功
            if($result){
                $this->success();
            }else{
                $this->error('网络异常，发货失败');
            }
        }
        $this->view->assign("lists", $lists); //可以发货
        $this->view->assign("data", $data);
        return $this->view->fetch();
    }

    /**
     * 评论管理
     */
    public function comment()
    {
        return $this->view->fetch('wanlshop/comment/index');
    }

    /**
     * 订单推送消息（方法内使用）
     *
     * @param string order_id 订单ID
     * @param string state 状态
     */
    private function pushOrder($order_id = 0, $state = '已发货')
    {
        $order = $this->model->get($order_id);
        $orderGoods = model('app\index\model\wanlshop\OrderGoods')
            ->where(['order_id' => $order_id])
            ->select();
        $msgData = [];
        foreach ($orderGoods as $goods) {
            $msg = [
                'user_id' => $order['user_id'], // 推送目标用户
                'shop_id' => $this->shop->id,
                'title' => '您的订单'.$state, // 推送标题
                'image' => $goods['image'], // 推送图片
                'content' => '您购买的商品 '.(mb_strlen($goods['title'],'utf8') >= 25 ? mb_substr($goods['title'],0,25,'utf-8').'...' : $goods['title']).' '.$state,
                'type' => 'order',  // 推送类型
                'modules' => 'order',  // 模块类型
                'modules_id' => $order_id,  // 模块ID
                'come' => '订单'.$order['order_no'] // 来自
            ];
            $msgData[] = $msg;
            $this->wanlchat->send($order['user_id'], $msg);
        }
        $notice = model('app\index\model\wanlshop\Notice')->saveAll($msgData);
    }

    public function downloadExcel(){
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        if(!isset($this->auth->id)){
            $this->error("用户信息有误");
        }else{
            $uid = $this->auth->id;
        }

        $shop_id = db("wanlshop_shop")->where("user_id",$uid)->find();
        if(!$shop_id){
            $this->error("用户未绑定商户,请核实后操作");
        }

        $data = [];
        $ids = input("param.ids");
        $filter = input("param.filter");
        $op = input("param.op");
        $filterArray = json_decode(html_entity_decode($filter), true);
        $opArray = json_decode(html_entity_decode($op), true);

        $where1 = [];
        $where1["shop_id"] = ["=",$shop_id["id"]];
        if (isset($filterArray['state']) && $filterArray['state'] !== '') {
            $op = isset($opArray['state']) ? $opArray['state'] : '=';
            $where1["state"] = [$op, $filterArray['state']];
        }
        if ($ids != "all"){
            $where1["order.id"] = ["in",explode(",",$ids)];
        }
        $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        // var_dump (["filter"=>($filter),'op'=>($op)]);
        // return;
        $list = $this->model
            ->with(['user','ordergoods'])
            ->where($where)
            ->where($where1)
            ->order($sort, $order)
            ->select();

        $excel = new Spreadsheet();
        $worksheet = $excel->getActiveSheet();
        $worksheet->setTitle('订单数据');

        // 设置默认样式
        $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $excel->getDefaultStyle()->getFont()->setSize(12);

        // 设置表头
        $headers = [
            'A' => ['title' => '编号', 'width' => 15],
            'B' => ['title' => '订单号', 'width' => 25],
            'C' => ['title' => '下单时间', 'width' => 20],
            'D' => ['title' => '用户名', 'width' => 20],
            'E' => ['title' => '用户手机号', 'width' => 20],
            'F' => ['title' => '收货姓名', 'width' => 15],
            'G' => ['title' => '联系电话', 'width' => 20],
            'H' => ['title' => '收货地址', 'width' => 40],
            'I' => ['title' => '商品信息', 'width' => 30],
            'J' => ['title' => '商品数量', 'width' => 15],
            'K' => ['title' => '快递名称', 'width' => 20],
            'L' => ['title' => '快递单号', 'width' => 25],
            'M' => ['title' => '备注', 'width' => 15],
            'N' => ['title' => '订单状态', 'width' => 15],
            'O' => ['title' => '订单金额', 'width' => 15],
            'P' => ['title' => '实际支付', 'width' => 15]
        ];

        // 设置列宽和表头
        foreach ($headers as $col => $header) {
            $worksheet->getColumnDimension($col)->setWidth($header['width']);
            $worksheet->setCellValue($col.'1', $header['title']);
        }

        // 设置表头样式
        $headerStyle = [
            'font' => ['bold' => true],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
            'borders' => ['allBorders' => ['style' => Border::BORDER_THIN]]
        ];
        $worksheet->getStyle('A1:P1')->applyFromArray($headerStyle);

        $rowIndex = 2; // 数据从第2行开始

        foreach ($list as $row) {
            $row->getRelation('user')->visible(['id','username','nickname',"mobile",'avatar']);
            $express_name = "";

            if(!empty($row['express_name'])){
                $express_name1 = model('app\index\model\wanlshop\Kuaidi')
                    ->where(['code' => $row['express_name']])
                    ->find();
                if($express_name1){
                    $express_name = $express_name1["name"];
                }
            }

            $row->pay = model('app\index\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                ->find();

            $row->address = model('app\index\model\wanlshop\OrderAddress')
                ->where('order_id',$row['id'])
                ->find();

            $goods_name = "";
            $num = 0;
            foreach ($row["ordergoods"] as $v1){
                $goods_name = $goods_name.$v1["title"];
                $num = bcadd($num,$v1["number"]);
            }

            // 逐单元格设置数据，特别是订单号和手机号等字段
            $worksheet->setCellValue('A'.$rowIndex, $row["id"]);
            $worksheet->setCellValueExplicit('B'.$rowIndex, $row["order_no"], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            $worksheet->setCellValue('C'.$rowIndex, $row["createtime_text"]);
            $worksheet->setCellValue('D'.$rowIndex, $row["user"]["username"]);
            $worksheet->setCellValueExplicit('E'.$rowIndex, $row["user"]["mobile"], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            $worksheet->setCellValue('F'.$rowIndex, $row["address"]["name"]);
            $worksheet->setCellValueExplicit('G'.$rowIndex, $row["address"]["mobile"], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            $worksheet->setCellValue('H'.$rowIndex, $row["address"]["address"]);
            $worksheet->setCellValue('I'.$rowIndex, $goods_name);
            $worksheet->setCellValue('J'.$rowIndex, $num);
            $worksheet->setCellValue('K'.$rowIndex, $express_name);
            $worksheet->setCellValueExplicit('L'.$rowIndex, $row["express_no"], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            $worksheet->setCellValue('M'.$rowIndex, "");
            $worksheet->setCellValue('N'.$rowIndex, $row["state_text"]);
            $worksheet->setCellValue('O'.$rowIndex, $row["pay"]["price"]);
            $worksheet->setCellValue('P'.$rowIndex, $row["pay"]["actual_payment"]);

            $rowIndex++;
        }

        // 设置数据区域样式
        $dataStyle = [
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
            'borders' => ['allBorders' => ['style' => Border::BORDER_THIN]]
        ];
        $worksheet->getStyle('A2:P'.($rowIndex-1))->applyFromArray($dataStyle);

        // 强制将数字格式设置为文本
        $worksheet->getStyle('B2:B'.($rowIndex-1))->getNumberFormat()->setFormatCode('@');
        $worksheet->getStyle('E2:E'.($rowIndex-1))->getNumberFormat()->setFormatCode('@');
        $worksheet->getStyle('G2:G'.($rowIndex-1))->getNumberFormat()->setFormatCode('@');
        $worksheet->getStyle('L2:L'.($rowIndex-1))->getNumberFormat()->setFormatCode('@');

        $title = date("YmdHis");

        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        $objWriter = IOFactory::createWriter($excel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }


    public function downloadExcel1(){
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        // $shop = db("wanlshop_shop")->select();
        // foreach ($shop as $v){
        //兴德
        $userid = 2;
        //慧选易购
        // $userid = 3;
        //中谷十
        // $userid = 4;
        //碧康清
        // $userid = 5;
        $shop_id = db("wanlshop_shop")->where("id",$userid)->find();
        if(!$shop_id){
            $this->error("用户未绑定商户,请核实后操作");
        }
        $data = [];
        $where1  = [];
        $where1["shop_id"]  = ["=",$shop_id["id"]];
        $list = $this->model
            ->with(['user','ordergoods'])
            ->where("state","in",[2,3,4,6])
            ->where($where1)
            ->select();
        foreach ($list as $row) {
            $express_name = "";
            if(!empty($row['express_name'])){
                $express_name1 = model('app\index\model\wanlshop\Kuaidi')
                    ->where(['code' => $row['express_name']])
                    ->find();
                if($express_name1){
                    $express_name = $express_name1["name"];
                }

            }
            $row->pay = model('app\index\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                ->find();
            $row->address = model('app\index\model\wanlshop\OrderAddress')
                ->where('order_id',$row['id'])
                ->find();
            $goods_name = "";
            $num = 0;
            foreach ($row["ordergoods"] as $v1){
                $goods_name = $goods_name.$v1["title"];
                $num = bcadd($num,$v1["number"]);
            }
            $data[] = [
                $row["id"],
                $row["order_no"],
                $row["createtime_text"],
                $row["address"]["name"],
                (string)$row["address"]["mobile"],
                $row["pay"]["price"],
                $row["pay"]["actual_payment"],
                $row["address"]["address"],
                $goods_name,
                $num,
                $express_name,
                (string)$row["express_no"],
                $row["state_text"],
            ];
        }
        $excel = new Spreadsheet();
        $excel->getProperties()
            ->setCreator("FastAdmin")
            ->setLastModifiedBy("FastAdmin")
            ->setTitle("订单数据")
            ->setSubject("Subject");
        $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $excel->getDefaultStyle()->getFont()->setSize(12);
        $excel->getDefaultStyle()->applyFromArray(
            array(
                'fill'      => array(
                    'type'  => Fill::FILL_SOLID,
                    'color' => array('rgb' => '000000')
                ),
                'font'      => array(
                    'color' => array('rgb' => "000000"),
                ),
                'alignment' => array(
                    'vertical'   => Alignment::VERTICAL_CENTER,
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'indent'     => 1
                ),
                'borders'   => array(
                    'allborders' => array('style' => Border::BORDER_THIN),
                )
            ));
        $worksheet = $excel->setActiveSheetIndex(0);
        $worksheet->setTitle('订单数据');
        $worksheet->getColumnDimension('B')->setWidth(20);
        $worksheet->getColumnDimension('C')->setWidth(20);
        $worksheet->getColumnDimension('D')->setWidth(20);
        $worksheet->getColumnDimension('G')->setWidth(25);
        $worksheet->getColumnDimension('H')->setWidth(25);
        $worksheet->getColumnDimension('K')->setWidth(20);
        $worksheet->getColumnDimension('L')->setWidth(35);
        $worksheet->setCellValue('A1', '编号');
        $worksheet->setCellValueExplicit('B1', '订单号',"str");
        $worksheet->setCellValueExplicit('C1', '下单时间',"str");
        $worksheet->setCellValueExplicit('D1', '用户名',"str");
        $worksheet->setCellValueExplicit('E1', '用户手机号',"str");
        $worksheet->setCellValue('F1', '订单金额');
        $worksheet->setCellValue('G1', '实际支付');
        $worksheet->setCellValueExplicit('H1', '收货地址',"str");
        $worksheet->setCellValue('I1', '商品信息');
        $worksheet->setCellValue('J1', '商品数量');
        $worksheet->setCellValue('K1', '快递名称');
        $worksheet->setCellValueExplicit('L1', '快递单号',"str");
        $worksheet->setCellValueExplicit('M1', '订单状态',"str");
        $worksheet->fromArray($data, NULL, 'A2');
        $excel->createSheet();
        $title = $shop_id["shopname"];
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = IOFactory::createWriter($excel, 'Xlsx');
        $objWriter->save('php://output');
    }




}
